table = [ (1000, "M"),
          (900, "CM"),
          (500, "D"),
          (400, "CD"),
          (100, "C"),
          (90, "XC"),
          (50, "L"),
          (40, "XL"),
          (10, "X"),
          (9, "IX"),
          (5, "V"),
          (4, "IV"),
          (1, "I") ]

def toRoman(nr):
    result = []
    
    for (value, digit) in table:
        while nr >= value:
            result.append(digit)
            nr -= value
            
    return "".join(result)

def fromRoman(string):
    result = 0
    
    for (value, digit) in table:
        while string.startswith(digit):
            result += value
            string = string[len(digit):]
            
    return result
    
file = open("roman.txt", "r")
saved = 0

for line in file:
    line = line.strip()
    processed = toRoman(fromRoman(line))
    if line != processed:
        nrSaved = len(line) - len(processed)
        print line, "->", processed, "(saved", nrSaved, "chars)"
        saved += nrSaved
        
print saved
